package analysis

import (
	"errors"
	"github.com/cihub/seelog"
	"irisysFtp/db"
	"strings"
)

type Analysis struct {
	DestPath string
	Data     []byte
}

func (analysis Analysis) AnalysisFile() (int64, error) {
	validDeviceFlow, err := analysis.AllDeviceFlow()
	if validDeviceFlow == nil {
		return int64(len(analysis.Data)), err
	}
	if err != nil {
		seelog.Error(err)
		return 0, err
	}
	// 发送并保持flow
	bo, err := SendAndSave(validDeviceFlow)
	if err != nil {
		return 0, err
	}
	//保存 文件路径
	analysis.SaveFileName()
	if bo {
		return int64(len(analysis.Data)), nil
	} else {
		seelog.Error("send != save")
		return 0, errors.New("send != save")
	}
}

func (analysis Analysis) FileType() string {
	destPath := analysis.DestPath
	split := strings.Split(destPath, "/")
	return split[1]
}

func (analysis Analysis) FileName() []string {
	destPath := analysis.DestPath
	split := strings.Split(destPath, "/")
	return split[1:]
}

/**
解析文件中的所有数据
*/
func (analysis Analysis) AllDeviceFlow() ([]*db.DeviceFlow, error) {
	fileType := analysis.FileType()
	switch fileType {
	case "skycount":
		return skyCount(&analysis)
	case "irisys":
		return irisy(&analysis)
	case "hella":
		return hella(&analysis)
	default:
		if strings.Contains(fileType, ".txt") {
			return irisy(&analysis)
		} else if strings.HasSuffix(analysis.DestPath, "_00.xml") {
			return winnerCount(&analysis)
		}
	}
	return nil, nil
}

/**
保存文件名称 用于删除 文件
*/
func (analysis Analysis) SaveFileName() {
	seelog.Infof("--- saveFile type: %v path:%v", analysis.FileType(), analysis.DestPath)
	fileType := analysis.FileType()
	path := analysis.DestPath
	switch fileType {
	case "skycount":
		path = strings.ReplaceAll(path, ".tmp", ".txt")

	}
	db.InsertFile(fileType, path)
}

/**
去除已经发送的
*/
//func (analysis Analysis) ValidDeviceFlow() ([]*db.DeviceFlow, error) {
//	allDeviceFlow, err := analysis.AllDeviceFlow()
//	if allDeviceFlow == nil {
//		return nil, nil
//	}
//	if err != nil {
//		return nil, err
//	}
//	newDF := *new([]*influxdb.DeviceFlow)
//	if len(allDeviceFlow) > 0 {
//		startTime := allDeviceFlow[0].Time.Format(util.DateTimeFormat)
//		endTime := allDeviceFlow[len(allDeviceFlow)-1].Time.Format(util.DateTimeFormat)
//		deviceId := allDeviceFlow[0].DeviceId
//		findDeviceFlow := conf.InfluxdbConnect().SelectDeviceFlowByDeviceIdAndTime(influxdb.Allflow, deviceId, startTime, endTime)
//		fdfMap := make(map[string]*influxdb.DeviceFlow, len(findDeviceFlow))
//		for _, val := range findDeviceFlow {
//			fdfMap[fmt.Sprintf("%v_%v_%v", val.DeviceId, val.Zone, val.Time)] = val
//		}
//		for _, val := range allDeviceFlow {
//			if fdfMap[fmt.Sprintf("%v_%v_%v", val.DeviceId, val.Zone, val.Time)] == nil {
//				newDF = append(newDF, val)
//			}
//		}
//		seelog.Infof("== new DeviceFlow len: %v", len(newDF))
//	}
//	return newDF, nil
//}
